from django.shortcuts import render

from django.db.models import Q
from django.shortcuts import render
from ihome.utils.views import LoginRequiredJsonMixin
from django.views import View
from django.http import *
import json
from users.models import User
from homes.models import House
from order.models import *
import datetime
# Create your views here.


# Create your views here.


class AddOrder(View,LoginRequiredJsonMixin):
    #添加订单
    def post(self,request):
        # 1:提取參數,house_id ,start)date,end)data
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 2:常規校驗參數
        if not all([house_id,start_date,end_date]):
            return JsonResponse({
                'errno':400,
                'errmsg':'缺少必要參數'
            })

        if start_date > end_date:
            return  JsonResponse({'code':400,'errmsg':'參數件數錯誤'})
        # 判斷用戶是否爲房屋主人
        # user = request.user
        # try:
        #     result = House.objects.get(user = user)
        #     return JsonResponse({
        #         'errno':400,
        #         'errmsg'
        #     })
        # except Exception:
        #     return JsonResponse({'code':400,'errmsg':'房間爲該用戶所有'})

        #判斷該時間段是否有人入住,並提交訂單
        start_date1 = datetime.datetime.strptime(start_date,'%Y-%m-%d')
        end_date1 = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        days = end_date1-start_date1
        days = days.days
        print(days)
        print(start_date,end_date)
        houses = Order.objects.filter(house_id = house_id).exclude(Q(begin_date__gt=end_date)|Q(end_date__lt=start_date))
        if houses:
            return JsonResponse({
                'errno':0,
                'errmsg':'時間衝突',
            })


        new_order = Order()
        try:
            house = House.objects.get(pk = house_id)
            user = request.user
            new_order.begin_date = start_date
            new_order.end_date = end_date
            new_order.user = user
            new_order.days = int(days)
            new_order.house_id = house_id
            new_order.house_price = house.price
            new_order.amount = house.price * days
            new_order.status = int(Order.ORDER_STATUS['WAIT_ACCEPT'])
            print(user.id,days,house_id,house.price,start_date, end_date,Order.ORDER_STATUS['WAIT_PAYMENT'])
            new_order.save()

        except Exception as e:
            print(e)
            return JsonResponse({'errno':4101,'errmsg':'提交訂單錯誤'})
        return JsonResponse({
            'errno': 0,
            'errmsg': '下單成功',
            'data': {
                'order_id':new_order.pk
            },


        })

    #订单列表
    def get(self,request):
        #提取參數
        user = request.user
        role = request.GET.get('role')
        #校驗參數,訂單是否尊在
        print(role)
        if role == 'custom':
            orders_obj = Order.objects.filter(user = user.id)
        elif role == 'landlord':
            houses = House.objects.filter(user = user.id)
            orders_obj = Order.objects.filter(house_id__in=[house.id for house in houses])

        #if not orders_obj:
           # return JsonResponse({'errno':400,'errmsg':"用戶訂單不存在"})

        #便利,提取數據庫數據

        orders = []
        for order in orders_obj:
            orders.append({
                'amount':order.amount,
                'comment':order.comment,
                'ctime':order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                'days':order.days,
                'end_date':str(order.end_date),
                'img_url':'',
                'order_id':order.pk,
                'start_date':order.begin_date,
                'status':Order.ORDER_STATUS_ENUM[order.status],
                'title':House.objects.get(pk=order.house_id).title,
            })
        print(orders)

        return JsonResponse({
            'errno':0,
            'errmsg':'ok',
            'data':{
                'orders':orders
            }
        })




#接单和拒单
class OrderManege(LoginRequiredJsonMixin,View):
    def put(self,request,order_id):
        #提取參數 action,reason
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')
        if action == 'accept':
            action = "WAIT_COMMENT"
        elif action == 'reject':
            action = "REJECTED"
        #基本校驗
        if not all([action,order_id]):
            return JsonResponse({'errno':400,'errmsg':'缺少鼻炎參數'})
        #判斷訂單屬於該用戶
        user = request.user
        order = Order.objects.get(pk = order_id)
        if not order:
            return  JsonResponse({"errno":400,'errmsg':'該用戶的此訂單不存在'})
        # 修改訂單的狀態和返回鄉音;
        try:
            order.status = Order.ORDER_STATUS[action]
            order.comment = reason
            order.save()
        except Exception:
            return JsonResponse({'errno':400,'errmsg':'數據庫錯誤'})

        return JsonResponse({
            'errno':0,
            'errmsg':'操作成功',
        })



class Critical(LoginRequiredJsonMixin,View):

    def put(self,request,order_id):
        #提取參數,comment
        user = request.user
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')

        #常規校驗
        if not comment:
            return JsonResponse({'errno':400,'errmsg':'參數不存在'})

        order_obj = Order.objects.get(pk = order_id)
        if not order_id:
                return JsonResponse({'errno':400,'errmsg':'訂單錯誤'})
        try:
            order_obj.comment = comment
            order_obj.status = Order.ORDER_STATUS['COMPLETE']
            order_obj.save()
        except Exception:
            return JsonResponse({
                'errno':400,
                'errmsg':'數據庫寫入錯誤',
            })

        return JsonResponse({
            'errno':0,
            'errmsg':'評論成功',

        })

